# encoding=utf-8
from __future__ import division
import MySQLdb
import datetime
import time
import json
import logging
import traceback
from powerModel_fp import getAllScore
from power_demo import getScored
from DBStory import cursor


def add_power_score(obj, ent_name, year):
    current_year = int(time.strftime('%Y', time.localtime(time.time())))
    if current_year != year:
        return obj
    electricity_score = None
    try:
        electricity_score = getJsonScore(ent_name)
    except Exception as e:
        print e
    # electricity_score = getScored()
    if electricity_score is None or electricity_score == "":
        electricity_score = 0
    if obj.index_total:
        obj.index_total = obj.index_total + electricity_score * 0.1
    obj.index_2_3 = obj.index_2_3 * 0.9 + electricity_score * 0.1
    obj.index_3_13 = electricity_score
    return obj


# 长期稳定性
def a1(value):
    now = datetime.datetime.now()
    year = now.year
    month = now.month
    day = now.day
    lastStar = str(year - 1) + str(month)
    lastEnd = str(year) + str(month)

    lastlaststart = str(year - 2) + str(month)
    lastlastEnd = lastStar

    sql1 = "select sum(TSETTLE_PQ) as powerAll from DED_ENT_ELEC_CONSUME WHERE YM>%s AND YM<%s AND POWER_ACCOUNT_NUM=%s"
    cursor.execute(sql1, (lastStar, lastEnd, value))
    lastPower = cursor.fetchone()

    sql2 = "select sum(TSETTLE_PQ) as powerAll from DED_ENT_ELEC_CONSUME WHERE YM>%s AND YM<%s AND POWER_ACCOUNT_NUM=%s"
    cursor.execute(sql2, (lastlaststart, lastlastEnd, value))
    lastlastPower = cursor.fetchone()
    try:
        value = lastPower[0] / lastlastPower[0]
    except:
        value = 0
    return value


def a1_formula(v):
    sql = "select DISTINCT POWER_ACCOUNT_NUM from DED_ENT_ELEC_CONSUME"
    cursor.execute(sql)
    infor = cursor.fetchall()
    value = 0
    for index in infor:
        a1_value = a1(str(index[0]))
        if a1_value > value:
            value = a1_value
    return 1 - abs(a1(v) - 1) / abs(value)


# 短期稳定性
def a2(value):
    now = datetime.datetime.now()
    year = now.year
    month = now.month
    day = now.day
    lastStar = str(year) + str(month - 2)
    lastEnd = str(year) + str(month)

    lastlaststart = str(year - 2) + str(month)
    lastlastEnd = str(year) + str(month)

    sql1 = "select sum(TSETTLE_PQ) as powerAll from DED_ENT_ELEC_CONSUME WHERE YM>%s AND YM<%s AND POWER_ACCOUNT_NUM=%s"
    cursor.execute(sql1, (lastStar, lastEnd, value))
    lastPower = cursor.fetchone()

    sql2 = "select sum(TSETTLE_PQ) as powerAll from DED_ENT_ELEC_CONSUME WHERE YM>%s AND YM<%s AND POWER_ACCOUNT_NUM=%s"
    cursor.execute(sql2, (lastlaststart, lastlastEnd, value))
    lastlastPower = cursor.fetchone()

    try:
        value = lastPower[0] / lastlastPower[0]
    except:
        value = 0
    return value


def a2_formula(v):
    sql = "select DISTINCT POWER_ACCOUNT_NUM from DED_ENT_ELEC_CONSUME"
    cursor.execute(sql)
    infor = cursor.fetchall()
    value = 0
    for index in infor:
        a1_value = a2(str(index[0]))
        if a1_value > value:
            value = a1_value
    return 1 - abs(a2(v) - 1) / abs(value)


# 开户时长
def a3(value):
    sql = "select BUILD_DATE from DED_ENT_POWER_BASEINFO WHERE POWER_ACCOUNT_NUM=%s"
    cursor.execute(sql, (value,))
    infor = cursor.fetchone()
    try:
        BUILD_DATE = infor[0]
        timeArray = time.strptime(BUILD_DATE, "%Y-%m-%d %H:%M:%S")
        BUILD_DATE = int(time.mktime(timeArray))  # 立户日期
        CURRENT_TIME = int(time.time())
        aa = int((CURRENT_TIME - BUILD_DATE) / 86400)  # tian
    except:
        aa = 0
    return aa


def a3_formula(v):
    sql = "select DISTINCT POWER_ACCOUNT_NUM from DED_ENT_POWER_BASEINFO"
    cursor.execute(sql)
    infor = cursor.fetchall()
    valueMax = 0
    valueMin = 0
    for index in infor:
        a1_value = a3(str(index[0]))
        if a1_value > valueMax:
            valueMax = a1_value
        if a1_value < valueMin:
            valueMin = a1_value

    a = a3(v) - valueMin
    b = valueMax - valueMin
    return round(a / b, 2)


# 用电量
def a4(value):
    # 打开数据库连接
    # db = MySQLdb.connect("192.168.80.159", "mydb3", "mydb3", "mydb3", charset='utf8')
    #
    # # 使用cursor()方法获取操作游标
    # cursor = db.cursor()
    now = datetime.datetime.now()
    year = now.year
    month = now.month
    day = now.day
    lastStar = str(year - 1) + str(month)
    lastEnd = str(year) + str(month)

    sql1 = "select sum(TSETTLE_PQ) as powerAll from DED_ENT_ELEC_CONSUME WHERE YM>%s AND YM<%s AND POWER_ACCOUNT_NUM=%s"
    cursor.execute(sql1, (lastStar, lastEnd, value))
    lastPower = cursor.fetchone()
    aa = lastPower[0]
    return aa


def a4_formula(v):
    sql = "select DISTINCT POWER_ACCOUNT_NUM from DED_ENT_ELEC_CONSUME"
    cursor.execute(sql)
    infor = cursor.fetchall()
    valueMax = 0
    valueMin = 0
    for index in infor:
        a1_value = a4(str(index[0]))
        if a1_value is None:
            continue
        if a1_value > valueMax:
            valueMax = a1_value
        if a1_value < valueMin:
            valueMin = a1_value

    a = a4(v) - valueMin
    b = valueMax - valueMin
    return round(a / b, 2)


# 开户时长
def a5(value):
    now = datetime.datetime.now()
    year = now.year
    month = now.month
    day = now.day
    lastStar = str(year - 1) + str(month)
    lastEnd = str(year) + str(month)

    sql1 = "select sum(RCVBL_AMT) as powerAll from DED_ENT_CUST_SHOULDPAY WHERE RCVBL_YM>%s AND RCVBL_YM<%s AND POWER_ACCOUNT_NUM=%s"
    cursor.execute(sql1, (lastStar, lastEnd, value))
    lastPower = cursor.fetchone()
    return lastPower[0]


def a5_formula(v):
    sql = "select DISTINCT POWER_ACCOUNT_NUM from DED_ENT_CUST_SHOULDPAY"
    cursor.execute(sql)
    infor = cursor.fetchall()
    valueMax = 0
    valueMin = 0
    for index in infor:
        a1_value = a5(str(index[0]))
        if a1_value is None:
            continue
        if a1_value > valueMax:
            valueMax = a1_value
        if a1_value < valueMin:
            valueMin = a1_value

    a = a5(v) - valueMin
    b = valueMax - valueMin
    return round(a / b, 2)


# 数据集合
def getJsonData(companyName):
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                        datefmt='%a, %d %b %Y %H:%M:%S',
                        filename='electricityModel.log',
                        filemode='w')
    try:
        sql = "select POWER_ACCOUNT_NUM from  DED_ENT_POWER_BASEINFO WHERE POWER_ACCOUNT_NAME=%s"
        cursor.execute(sql, (companyName,))
        infor = cursor.fetchone()
        v = infor[0]
        a = round(a1_formula(v), 2)
        b = round(a2_formula(v), 2)
        c = round(a3_formula(v), 2)
        d = round(a4_formula(v), 2)
        e = round(a5_formula(v), 2)
        data = {
            "longterm": {
                'name': '长期稳定性',
                'score': round(a * 0.4 * 0.35 * 0.5, 2),
                'value': a1(v),
            },
            "shortterm": {
                'name': '短期稳定性',
                'score': round(b * 0.6 * 0.35 * 0.5, 2),
                'value': a2(v),
            },
            "accTime": {
                'name': '开户时长',
                'score': round(c * 1 * 0.25 * 0.5, 2),
                'value': a3(v),
            },
            "electricity": {
                'name': '用电量',
                'score': round(d * 0.6 * 0.4 * 0.5, 2),
                'value': a4(v),
            },
            "elecost": {
                'name': '电费',
                'score': round(e * 0.4 * 0.4 * 0.5, 2),
                'value': a5(v),
            }
        }

        jsonDataZfp = getAllScore(v)
        all = dict(data.items() + jsonDataZfp.items())
        print all
        return all
    except:
        err_message = traceback.format_exc()
        print err_message
        logging.error(err_message)
        pass


# 指标得分
def getJsonScore(companyName):
    allList = getJsonData(companyName)
    sumScore = sum(allList[key]["score"] for key in allList)
    print  round(sumScore, 2)
    return round(sumScore, 2)


if __name__ == '__main__':
    getJsonData("淮安金太阳电力有限公司")
